/*
 * Created on 2008-5-23
 *
 * TODO
 */
package jacky.lanlan.song.extension.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

import jacky.lanlan.song.closure.Handler;
import jacky.lanlan.song.reflection.PackageUtils;

/**
 * 增加了自动扫描并注册<code>Entity</code>的功能。
 * 
 * @author Jacky.Song
 */
public class EnhancedASFactoryBean extends
		AnnotationSessionFactoryBean {

	private List<Class<?>> entities;
	
	/**
	 * 设置 Entity 所在包，这个Bean会自动递归查找并装载指定包及其子包下的 Entity 对象。
	 * 
	 * @param packName
	 *          <code>Entity</code>所在包包名
	 */
	public void setEntityBasePackages(String... packNames) {
		entities = new ArrayList<Class<?>>(50);
		for(String name : packNames) {
			PackageUtils.doWithClassInPackage(name, new Handler<Class<?>>() {
				public void doWith(Class<?> beanClass) {
					if(beanClass.isAnnotationPresent(javax.persistence.Entity.class)) {
						entities.add(beanClass);
					}
				}
			});
		}
	}
	
	@Override
	protected void postProcessAnnotationConfiguration(
			AnnotationConfiguration config) throws HibernateException {
		for (Class<?> persistentClass : entities) {
			config.addAnnotatedClass(persistentClass);
		}
		// 不再需要entities
//		entities.clear();
//		entities=null;
	}
	
}
